#!/bin/bash

manSuffix=( 0 1 2 3 4 5 6 7 8 9 0x 1x 2x 3x 4x 5x 6x 7x 8x 9x 0p 1p 2p 3p 4p 5p 6p 7p 8p 9p n )
#manSuffix=( 8 )
#echo ${manSuffix[@]}

manFolders=( /usr/share/man/man /usr/man/man /usr/local/man/man /usr/local/share/man/man /usr/X11R6/man/man /opt/share/man/man /opt/man/man /opt/local/man/man /opt/local/share/man/man )
#manFolders=( /opt/share/man/man )
#echo ${manFolders[@]}

extcmd=( "*.gz" "gzip -dqf " "*.bz2" "bzip2 -dqf " "*.lzma" "lzma -dqf " "*.Z" "gzip -dqf " )
#echo  ${extcmd[@]}
declare -i extension
extension1="*.[0-9]"
extension2="*.[0-9][a-z]"
extension3="*.[0-9][a-z][a-z]"
if [ -z $1 ]
then
	echo "WARN: No compression specified"
	echo "FRMT: compressman {gz|bz2|lzma|Z}"
	exit 0
elif [ $1 = "gz" ]
then
	echo "INFO: gzip compress selected"
	extension=0
	extcmd[0]=$extension1
	extcmd[1]="gzip -q "
elif [ $1 = "bz2" ]
then
	echo "INFO: bzip2 compression selected"
	extension=2
	extcmd[2]=$extension1
	extcmd[3]="bzip2 -q "
elif [ $1 = "lzma" ]
then
	echo "INFO: lzma compression selected"
	extension=4
	extcmd[4]=$extension1
	extcmd[5]="lzma -q "
elif [ $1 = "Z" ]
then
	echo "INFO: gzip compression selected"
	extension=6
	extcmd[6]=$extension1
	extcmd[7]="gzip -q -S .Z "
else
	echo "ERRR: Unknown compression specified"
	echo "FRMT: fixman {gz|bz2|lzma|Z}"
	exit 1
fi

#echo  ${extcmd[@]} 
#echo  ${extcmd[$extension]} 
#echo  ${extcmd[$extension+1]}

for folder in ${manFolders[@]}
do
	for suffix in ${manSuffix[@]}
	do 
		if [ -d "$folder$suffix" ]
		then
			cd "$folder$suffix"
			echo "INFO: CWD = $PWD"
			echo "INFO: Replacing symbolic links with dereferencing manuals"

			syms=(`ls -F 2>/dev/null| grep @ | sed -e 's/@//g' | awk -F"." '{print $0" "$NF}'`)
			declare -i nsyms=${#syms[@]}
			symlinks=(`ls -l 2>/dev/null| grep ^l | awk -F " " '{ print $10" "$8}'`)
			declare -i i
			mandir=`pwd | awk -F "/" '{print $NF}'`
			for (( i=0; i<nsyms; i=i+2 ))
			do 
				rm -f "${syms[$i]}"
				if [ ${syms[$i+1]} == "gz"  ] || [ ${syms[$i+1]} == "bz2" ] || [ ${syms[$i+1]} == "lzma" ] || [ ${syms[$i+1]} == "Z" ]
				then 
					echo ".so $mandir/${symlinks[i]/\.${syms[$i+1]}/}" > ${syms[i]/\.${syms[$i+1]}/}
				else
					echo ".so $mandir/${symlinks[i]}" > ${syms[$i]}		
				fi
			done

			echo "INFO: $1 Compressing manuals in $folder$suffix"
			for (( i=0; i<8; i=i+2))
			do 
				if [ $extension -ne $i ]
				then 
					echo "INFO: Decompressing ${extcmd[$i+1]} ${extcmd[$i]}"
					files=`ls ${extcmd[$i]} 2>/dev/null`
					if [ -n "$files" ]
					then
						command="${extcmd[$i+1]} $files"
						$command
					fi 
				fi
			done
			echo "INFO: $1 Compressing Extensions: $extension1 $extension2 $extension3"
			files=`ls $extension1 $extension2 $extension3 2>/dev/null`
			if [ -n "$files" ]
			then
				command="${extcmd[$extension+1]} $files"
				$command
			fi
		fi 
	done
done

